'use strict';
const Service = require('egg').Service;

class AdminService extends Service {
  // 添加管理员
  async insertOneAdmin(data) {
    const ctx = this.ctx;
    return await ctx.model.Admin.create({
      admin_account: data.account,
      admin_password: data.password,
      admin_name: data.name,
      add_time: Date.now(),
      admin_status: 1,
      identity: 1
    });
  }

  // 通过账号查找某个管理员
  async findAdminByAccount(admin_account) {
    const { ctx } = this;
    return await ctx.model.Admin.findOne({
      admin_account,
    });
  }

  // 通过_id查找某个管理员
  async findAdminById(id) {
    return await this.ctx.model.Admin.findById(id);
  }

  // 验证管理员账号密码
  async authAdmin(account, password) {
    const admin = await this.findAdminByAccount(account);
    if (!admin) {
      // 查无此人
      return {
        errcode: 1,
        msg: "管理员账号不存在"
      };
    }
    if (admin.admin_password !== password) {
      // 密码错误
      return {
        errcode: -1,
        msg: "密码错误"
      };
    }
    return {
      errcode: 0,
      msg: "success",
      data: admin
    };
  }

  // 查询管理员
  async searchAdmin(conditions) {
    const ctx = this.ctx;
    const keyword = new RegExp(conditions.keyword, 'i');
    const page = conditions.page || 1;
    const pageSize = conditions.pageSize || 10;
    const query = {
      admin_name: { $regex: keyword }
    };

    const [list, total] = await Promise.all([
      ctx.model.Admin.find(query)
        .select('-admin_password')
        .sort('admin_account')
        .skip((page - 1) * pageSize)
        .limit(pageSize),
      ctx.model.Admin.find(query).count(),
    ]);

    return {
      list,
      paging: ctx.helper.getPaging(total, pageSize)
    };
  }

    // // 修改管理员信息
    // async updateAdmin(data) {
    //   const { ctx } = this;
    //   const newData = {
    //     repairmen_name: data.name
    //   };
    //   if (data.password) {
    //     newData.repairmen_password = data.password;
    //   }
    //   await ctx.model.Repairmen.findByIdAndUpdate(data._id, newData);
    //   return { errcode: 0 };
    // }
}

module.exports = AdminService;
